//倒计时管理
import { ref, computed, watch } from "vue";
import { calculatePercentage } from "@/utils/common";
import { formatSeconds } from "@/utils/date";
import localAudio from "@/assets/audio/audio_end_01.mp3";
import { addFocusRecord, focusRecords } from "./record";
import { settings } from "./setting";
import { openDialog } from "./dialog";
import { isDevelopment } from "@/utils/env";

/**
 * 专注状态(专注中 focus、休息中 rest)
 */
export const status = ref("focus");
/**
 * 运行状态
 */
export const isRunning = ref(false);
/**
 * 定时器
 */
export const timer = ref(null);
/**
 * 总时长
 */
export const totoalTime = ref(0);
/**
 * 剩余时长
 */
export const remainingTime = ref(0);
/**
 * 开始按钮禁用状态
 */
export const startBtnDisabled = ref(false);
/**
 * 暂停按钮禁用状态
 */
export const pauseBtnDisabled = ref(true);
/**
 * 跳过按钮可见性
 */
export const jumpBtnVisible = ref(false);

/**
 * 圆形进度条百分比进度
 */
export const progress = computed(() => {
  return calculatePercentage(remainingTime.value, totoalTime.value, 2, false);
});

/**
 * 计算文字进度
 */
export const progressText = computed(() => {
  return formatSeconds(remainingTime.value);
});

/**
 * 提示文字计算属性
 * 根据倒计时状态显示不同的提示信息
 */
export const tipsText = computed(() => {
  // 倒计时未运行
  if (isRunning.value === false) {
    return `今日已专注${focusRecords.value.length}个番茄钟`;
  }
  // 倒计时运行中
  if (status.value === "focus") {
    return `专注中，今日已专注${focusRecords.value.length}个番茄钟`;
  } else {
    return `休息中，今日已专注${focusRecords.value.length}个番茄钟`;
  }
});

/**
 * 播放结束音频
 */
export const audioPlay = () => {
  // 检查配置决定要不要播放音频
  if (!settings.value.reminderSound) {
    return;
  }

  //播放默认音频
  const audio = new Audio(localAudio);
  audio.play();
};

/**
 * 显示系统提示
 */
export const showNotification = () => {
  // 检查配置决定要不要播放音频
  if (!settings.value.reminderNotification) {
    return;
  }
  if (status.value === "focus") {
    utools.showNotification("专注结束了！");
  } else {
    utools.showNotification("休息结束了！");
  }
};

/**
 * 倒计时初始化
 */
export const initCountdown = () => {
  // 恢复按钮状态
  startBtnDisabled.value = false;
  pauseBtnDisabled.value = true;

  if (status.value === "focus") {
    // 专注状态初始化，为了方便测试（开发环境为了方便测试，使用更短时长）
    totoalTime.value = isDevelopment() ? settings.value.focusDuration : settings.value.focusDuration * 60;

    remainingTime.value = totoalTime.value;
  } else {
    // 休息状态初始化，为了方便测试（开发环境为了方便测试，使用更短时长）
    totoalTime.value = isDevelopment() ? settings.value.restDuration : settings.value.restDuration * 60;

    remainingTime.value = totoalTime.value;
  }
};

/**
 * 开始倒计时
 */
export const onStart = () => {
  // 运行状态置为开启
  isRunning.value = true;

  // 控制按钮状态
  startBtnDisabled.value = true;
  pauseBtnDisabled.value = false;

  clearInterval(timer.value);
  // 启动定时器
  timer.value = setInterval(() => {
    remainingTime.value = remainingTime.value - 1;
    // 倒计时结束
    if (remainingTime.value <= 0) {
      // 清除定时器
      clearInterval(timer.value);
      // 运行状态置为关闭
      isRunning.value = false;
      // 播放音频
      audioPlay();
      // 系统提示
      showNotification();
      if (status.value === "focus") {
        focusEnded();
      } else {
        restEnded();
      }
    }
  }, 1000);
};

/**
 * 专注结束引导对话框
 */
const focusEndedDialog = () => {
  openDialog(
    "专注结束，是否休息一下？",
    "OK",
    "取消",
    () => {
      status.value = "rest";
      jumpBtnVisible.value = true;
      initCountdown();
      onStart();
    },
    () => {
      status.value = "focus";
      initCountdown();
    }
  );
};

/**
 * 专注结束回调
 */
const focusEnded = () => {
  // 添加专注记录
  addFocusRecord();
  // 开启了自动开始休息
  if (settings.value.autoStartRest) {
    status.value = "rest";
    jumpBtnVisible.value = true;
    initCountdown();
    onStart();
    return;
  }

  // 没有开启自动休息，通过对话框决定下一步
  focusEndedDialog();
};

/**
 * 休息结束引导对话框
 */
const restEndedDialog = () => {
  openDialog(
    "休息结束，是否开启下一轮专注？",
    "OK",
    "取消",
    () => {
      status.value = "focus";
      jumpBtnVisible.value = false;
      initCountdown();
      onStart();
    },
    () => {
      status.value = "focus";
      jumpBtnVisible.value = false;
      initCountdown();
    }
  );
};

/**
 * 休息结束回调
 */
const restEnded = () => {
  // 开启了自动开始专注
  if (settings.value.autoStartFocus) {
    status.value = "focus";
    jumpBtnVisible.value = false;
    initCountdown();
    onStart();
    return;
  }

  // 没有开启自动开始专注，通过对话框决定下一步
  restEndedDialog();
};

/**
 * 暂停倒计时
 */
export const onPause = () => {
  // 清除定时器
  clearInterval(timer.value);
  // 控制按钮状态
  startBtnDisabled.value = false;
  pauseBtnDisabled.value = true;
};

/**
 * 跳过休息
 */
export const onJump = () => {
  // 清除定时器
  clearInterval(timer.value);
  // 运行状态置为关闭
  isRunning.value = false;

  // 休息结束提示
  restEndedDialog();
};

/**
 * 重置倒计时
 */
export const onReset = () => {
  // 清除定时器
  clearInterval(timer.value);
  // 运行状态置为关闭
  isRunning.value = false;

  status.value = "focus";
  jumpBtnVisible.value = false;
  initCountdown();
};

/**
 * 监听配置变化
 */
export const watchSettings = () => {
  watch(
    settings,
    () => {
      // 如果倒计时没有运行，修改配置的同时需要修改总时长、剩余时长、进度
      if (!isRunning.value) {
        initCountdown(settings.value);
      }
    },
    { deep: true } // 深度监听，确保对象内部属性变化也能被监听到
  );
};
